﻿using System;
using System.Data;
using System.IO;
using System.Web;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using msBsc.AppLogic.Cfg;
using msBsc.SvRef;
using System.Runtime.Serialization.Formatters.Binary;

namespace msBsc.AppLogic.DataAlc
{
    //public class SysFileInfo
    //{
    //    public string strVPath { get; set; }
    //    public string strSaveName { get; set; }
    //    public System.IO.FileInfo oFileInfo { get; set; }
    //}

    public class CBizSysFile : CustBizObject
    {


        private CDmSysFile m_CDmSysFile = new CDmSysFile();
        private CDmSysFile oDmSysFile
        {
            get { return m_CDmSysFile; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizSysFile()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmSysFile.SYS_FILE);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["FILE_ID"];
            //this.DataObj.IdGroup = "RID";
        }

        /********************************类属性方法等****************************************************************************************/
        //#region 类属性方法等


        //public DataSet Update()
        //{
        //    return Update("", true);
        //}

        //public DataSet Update(string strNotUpper, bool blIsRecord)
        //{
        //    if (drCurrDataRow != null && this.dsCurrDataSet != null)
        //    {
        //        DataSet dsRettem1 = Update(dsCurrDataSet, strNotUpper, blIsRecord);
        //        dsCurrDataSet.AcceptChanges();
        //        return dsRettem1;
        //    }
        //    return null;
        //}

        //public override DataSet Update(DataSet ds)
        //{
        //    this.dsCurrDataSet = ds;
        //    return base.Update(ds);
        //}

        //public override DataSet Update(DataSet ds, string strNotUpper, bool blIsRecord)
        //{
        //    this.dsCurrDataSet = ds;
        //    return base.Update(ds, strNotUpper, blIsRecord);
        //}


        //public DataRow GetAddNew(string strId)
        //{
        //    if (strId == string.Empty || strId.Length < 15)
        //    {
        //        strId = this.DataObj.NewID();
        //        dsCurrDataSet = new CDmSysFile();
        //    }
        //    else if (strCurrKeyId == strId)
        //    {
        //        if (drCurrDataRow != null)
        //        {
        //            return drCurrDataRow;
        //        }
        //        else
        //        {
        //            dsCurrDataSet = new CDmSysFile();
        //        }
        //    }
        //    else
        //    {
        //        dsCurrDataSet = SelectById(strId);
        //        if (dsCurrDataSet.Tables[0].Rows.Count > 0)
        //        {
        //            drCurrDataRow = dsCurrDataSet.Tables[0].Rows[0];
        //            strCurrKeyId = strId;
        //            return drCurrDataRow;
        //        }
        //    }

        //    drCurrDataRow = dsCurrDataSet.Tables[0].NewRow();
        //    drCurrDataRow[this.KeyFieldName] = strId; 
        //    strCurrKeyId = strId;
        //    dsCurrDataSet.Tables[0].Rows.Add(drCurrDataRow);
        //    //默认值 
        //    return drCurrDataRow;
        //}


        //public string UploadFile(System.IO.FileInfo ofinfo
        //    ,string strRelId
        //    ,string strRelType1
        //    ,string strRelType2
        //    ,string strFileNo
        //    ,string strFileNme
        //    , string strRemarks,bool blSaveCurrServer)
        //{
        //    string strRetId = "";
        //    string strSaveServer = Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_SAVE_SERVER");
        //    //if (!blSaveCurrServer && !string.IsNullOrEmpty(strSaveServer))
        //    //{
        //    //    //远程保存文件
        //    //    SRWebClient oSRWebClient = new SRWebClient();

        //    //    System.Collections.Specialized.NameValueCollection ooo=new System.Collections.Specialized.NameValueCollection();
        //    //    ooo.Add("F_UPLOAD", "1");
        //    //    ooo.Add("SVC_F_SAVE", "1");
        //    //    ooo.Add("USER_CRY", oSRWebClient.GetLoginUserCry());
        //    //    ooo.Add("REL_ID", strRelId);
        //    //    ooo.Add("REL_TYPE1", strRelType1);
        //    //    ooo.Add("REL_TYPE2", strRelType2);
        //    //    ooo.Add("FILE_NO", strFileNo);
        //    //    ooo.Add("FILE_NME", strFileNme);
        //    //    ooo.Add("REMARKS", strRemarks);
        //    //    string strRWJson = oSRWebClient.HttpPostData(strSaveServer + "pgajax.axd?F_UPLOAD=1&SVC_F_SAVE=1", 2000, strFileNme, ofinfo.FullName, ooo);
        //    //}
        //    //else
        //    //{
        //        string strCurrServer = Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_CURR_SERVER");
        //        string strVpath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDirV + ofinfo.Name;
        //        string strPath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDir + ofinfo.Name;
        //        System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
        //        transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
        //        transactionOption.Timeout = new TimeSpan(0, 10, 0);
        //        using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
        //        {
        //            using (CBizSysFile ofile = new CBizSysFile())
        //            {
        //                DataRow drNew = ofile.GetAddNew("");
        //                drNew["FILE_NO"] = strFileNo;
        //                drNew["FILE_NME"] = strFileNme;
        //                drNew["REMARKS"] = strRemarks;
        //                drNew["RELATION_ID"] = strRelId;
        //                drNew["RELATION_TYPE_CID1"] = strRelType1;
        //                drNew["RELATION_TYPE_CID2"] = strRelType2;
        //                drNew["SERVER_HTTP"] = strCurrServer;
        //                drNew["FILE_V_PATH"] = strVpath;
        //                drNew["FILE_PATH"] = strPath;
        //                drNew["FILE_EXT"] = ofinfo.Extension.Replace(".", "");
        //                drNew["FILE_SIZE"] = ofinfo.Length / 1024;
        //                ofile.Update();
        //                strRetId = drNew["FILE_ID"].ToString();
        //            }

        //            ofinfo.CopyTo(strPath, true);
        //            ts.Complete();
        //        }
        //    //}
        //    return strRetId;
        //}

        ///// <summary>
        ///// 根据文件ID获取文件信息
        ///// </summary>
        ///// <param name="strpFileId"></param>
        ///// <param name="strpHasSeekServerList"></param>
        ///// <returns></returns>
        //private System.IO.FileInfo GetFileInfoByFileId(string strpFileId, ref string strpSaveFname, ref string strpHasSeekServerList)
        //{
        //    //判断当前服务器是否处理过下载
        //    if (strpHasSeekServerList.ToUpper().IndexOf(Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_CURR_SERVER").ToUpper()) != -1)
        //    {
        //        return null ;
        //    }
        //    strpHasSeekServerList += string.IsNullOrEmpty(strpHasSeekServerList) ? Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_CURR_SERVER") : ";" + Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_CURR_SERVER");



        //    using (CBizSysFile objfile = new CBizSysFile())
        //    {
        //        objfile.strCurrKeyId = strpFileId;

        //        if (objfile.drCurrDataRow != null)
        //        {
        //            if (objfile.drCurrDataRow["IS_DIR"].ToString() == "True")
        //            {
        //                return null;
        //            }

        //            if (string.IsNullOrEmpty(strpSaveFname))
        //            {
        //                strpSaveFname = objfile.drCurrDataRow["FILE_NME"].ToString();
        //            }

        //            //从数据库读取文件
        //            if (objfile.drCurrDataRow["FILE_C"] != DBNull.Value)
        //            {
        //                byte[] fileData = (byte[])objfile.drCurrDataRow["FILE_C"];
        //                if (fileData != null)
        //                {
        //                    string strToFileName = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.RandomFileNme + "." + objfile.drCurrDataRow["FILE_EXT"].ToString();
        //                    string strToPath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + strToFileName;
        //                    using (System.IO.FileStream fs = new System.IO.FileStream(strToPath, System.IO.FileMode.OpenOrCreate))
        //                    {
        //                        using (System.IO.MemoryStream ms = new System.IO.MemoryStream(fileData))
        //                        {
        //                            ms.WriteTo(fs);
        //                            ms.Close();
        //                            fs.Close();
        //                            return new FileInfo(strToPath);
        //                        }
        //                    }
        //                }
        //            }

        //            //读取硬盘文件 
        //            if (File.Exists(objfile.drCurrDataRow["FILE_PATH"].ToString()))
        //            {
        //                return new FileInfo(objfile.drCurrDataRow["FILE_PATH"].ToString());
        //            }
        //            if (!string.IsNullOrEmpty(objfile.drCurrDataRow["FILE_V_PATH"].ToString()))
        //            {
        //                if (File.Exists(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.FileAppPathDir + objfile.drCurrDataRow["FILE_V_PATH"].ToString()))
        //                {
        //                    return new FileInfo(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.FileAppPathDir + objfile.drCurrDataRow["FILE_V_PATH"].ToString());
        //                }
        //                if (HttpContext.Current != null)
        //                {
        //                    if (File.Exists(HttpContext.Current.Server.MapPath(objfile.drCurrDataRow["FILE_V_PATH"].ToString())))
        //                    { 
        //                        return new FileInfo(HttpContext.Current.Server.MapPath(objfile.drCurrDataRow["FILE_V_PATH"].ToString()));
        //                    }
        //                    if (File.Exists(HttpContext.Current.Server.MapPath(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + objfile.drCurrDataRow["FILE_V_PATH"].ToString())))
        //                    {
        //                        return new FileInfo(HttpContext.Current.Server.MapPath(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + objfile.drCurrDataRow["FILE_V_PATH"].ToString()));
        //                    }
        //                    if (File.Exists(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + objfile.drCurrDataRow["FILE_V_PATH"].ToString()))
        //                    {
        //                        return new FileInfo(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + objfile.drCurrDataRow["FILE_V_PATH"].ToString());
        //                    }
        //                    if (File.Exists(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDir + objfile.drCurrDataRow["FILE_V_PATH"].ToString()))
        //                    {
        //                        return new FileInfo(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDir + objfile.drCurrDataRow["FILE_V_PATH"].ToString());
        //                    }
        //                }
        //            }

        //            //获取远程服务器文件
        //            if (!string.IsNullOrEmpty(objfile.drCurrDataRow["SERVER_HTTP"].ToString()) && objfile.drCurrDataRow["SERVER_HTTP"].ToString().ToUpper() != Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_CURR_SERVER").ToUpper())
        //            {  
        //                if (strpHasSeekServerList.IndexOf(objfile.drCurrDataRow["SERVER_HTTP"].ToString()) == -1)
        //                {
        //                    SRWebClient oSRWebClient = new SRWebClient();
        //                    string strSavetem1 = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.RandomFileNme + "." + objfile.drCurrDataRow["FILE_EXT"].ToString();
        //                    long lgFileLen = oSRWebClient.DownloadFile(objfile.drCurrDataRow["SERVER_HTTP"].ToString() + "filedown.axd?FILE_ID=" + strpFileId + "&USER_CRY=" + oSRWebClient.GetLoginUserCry() + "&SERVER_LIST=" + strpHasSeekServerList, strSavetem1, true);

        //                    strpHasSeekServerList += string.IsNullOrEmpty(strpHasSeekServerList) ? objfile.drCurrDataRow["SERVER_HTTP"].ToString() : ";" + objfile.drCurrDataRow["SERVER_HTTP"].ToString();

        //                    if (lgFileLen > 0)
        //                    {
        //                        if (File.Exists(strSavetem1))
        //                        {
        //                            return new FileInfo(strSavetem1);
        //                        }
        //                    }
        //                }
        //            }

        //            //通过虚拟路径从备用服务器取
        //            string strFileBakServerList = Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_BAK_SERVER").Split(';')[0];
        //            if (!string.IsNullOrEmpty(strFileBakServerList) && strFileBakServerList.ToUpper() != Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_CURR_SERVER").ToUpper())
        //            {
        //                if (strpHasSeekServerList.IndexOf(strFileBakServerList) == -1)
        //                {
        //                    SRWebClient oSRWebClient = new SRWebClient();
        //                    string strSavetem1 = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.RandomFileNme + "." + objfile.drCurrDataRow["FILE_EXT"].ToString();
        //                    long lgFileLen = oSRWebClient.DownloadFile(strFileBakServerList + "filedown.axd?FILE_ID=" + strpFileId + "&USER_CRY=" + oSRWebClient.GetLoginUserCry() + "&SERVER_LIST=" + strpHasSeekServerList, strSavetem1, true);

        //                    strpHasSeekServerList += string.IsNullOrEmpty(strpHasSeekServerList) ? strFileBakServerList : ";" + strFileBakServerList;

        //                    if (lgFileLen > 0)
        //                    {
        //                        if (File.Exists(strSavetem1))
        //                        {
        //                            return new FileInfo(strSavetem1);
        //                        }
        //                    }
        //                }
        //            }
        //        }
        //    }

        //    return null;
        //}


        ///// <summary>
        ///// 获取文件信息
        ///// </summary>
        ///// <param name="strpFileId"></param>
        ///// <param name="strpFileNme"></param>
        ///// <param name="strpSaveFname"></param>
        ///// <param name="strpHasSeekServerList">已经查询过该文件的服务器列表</param>
        ///// <returns></returns>
        //public FileInfo GetFileInfo(string strpFileId, string strpFileNme, string strpSaveFname, string strpHasSeekServerList)
        //{
        //    if (File.Exists(strpFileNme))
        //    {
        //        return new FileInfo(strpFileNme); 
        //    }
        //    if (File.Exists(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + strpFileNme))
        //    {
        //        return new FileInfo(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + strpFileNme); 
        //    }
        //    if (File.Exists(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDir + strpFileNme))
        //    {
        //        return new FileInfo(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDir + strpFileNme); 
        //    }
        //    if (File.Exists(HttpContext.Current.Server.MapPath(strpFileNme)))
        //    {
        //        return new FileInfo(HttpContext.Current.Server.MapPath(strpFileNme)); 
        //    }
        //    if (File.Exists(HttpContext.Current.Server.MapPath(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + strpFileNme)))
        //    {
        //        return new FileInfo(HttpContext.Current.Server.MapPath(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + strpFileNme)); 
        //    }
        //    if (!string.IsNullOrEmpty(strpFileId))
        //    {
        //        System.IO.FileInfo objFileInfo = GetFileInfoByFileId(strpFileId, ref strpSaveFname, ref strpHasSeekServerList);
        //        if (objFileInfo != null && objFileInfo.Exists)
        //        { 
        //            return objFileInfo;
        //        }
        //    }



        //    //通过虚拟路径从备用服务器取
        //    if (!string.IsNullOrEmpty(strpFileNme))
        //    {
        //        string strFileBakServerList = Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_BAK_SERVER").Split(';')[0];
        //        if (!string.IsNullOrEmpty(strFileBakServerList) && strFileBakServerList.ToUpper() != Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_CURR_SERVER").ToUpper())
        //        {
        //            if (strpHasSeekServerList.IndexOf(strFileBakServerList) == -1)
        //            {
        //                SRWebClient oSRWebClient = new SRWebClient();
        //                string strToFileName = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.RandomFileNme + strpFileNme.Substring(strpFileNme.LastIndexOf("."));
        //                string strSavetem1 = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + strToFileName;
        //                long lgFileLen = oSRWebClient.DownloadFile(strFileBakServerList + "filedown.axd?FILE_ID=" + strpFileId + "&file=" + strpFileNme + "&FSNME=" + strpSaveFname + "&USER_CRY=" + oSRWebClient.GetLoginUserCry() + "&SERVER_LIST=" + strpHasSeekServerList, strSavetem1, true);

        //                strpHasSeekServerList += string.IsNullOrEmpty(strpHasSeekServerList) ? strFileBakServerList : ";" + strFileBakServerList;

        //                if (lgFileLen > 0)
        //                {
        //                    if (File.Exists(strSavetem1))
        //                    {
        //                        return new FileInfo(strSavetem1);
        //                    }
        //                }
        //            }
        //        }
        //    }

        //    return null;
        //}



        ///// <summary>
        ///// 根据传人的参数下载文件，适用网站模式
        ///// </summary>
        ///// <param name="strpFileId"></param>
        ///// <param name="strpFileNme"></param>
        ///// <param name="strpSaveFname"></param>
        ///// <param name="strpHasSeekServerList">已经查询过该文件的服务器列表</param>
        ///// <returns></returns>
        //public bool FileDownLoad(string strpFileId, string strpFileNme, string strpSaveFname,string strpHasSeekServerList)
        //{
        //    System.IO.FileInfo objFileInfo = GetFileInfo(strpFileId, strpFileNme, strpSaveFname, strpHasSeekServerList);
        //    if (objFileInfo!=null && objFileInfo.Exists)
        //    {
        //        FileDownByFileInfo(objFileInfo, strpSaveFname);
        //        return true;
        //    }
        //    return false;



        //    //if (File.Exists(strpFileNme))
        //    //{
        //    //    System.IO.FileInfo objFileInfo = new FileInfo(strpFileNme);
        //    //    FileDownByFileInfo(objFileInfo, strpSaveFname);
        //    //    return true;
        //    //}
        //    //if (File.Exists(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + strpFileNme))
        //    //{
        //    //    System.IO.FileInfo objFileInfo = new FileInfo(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + strpFileNme);
        //    //    FileDownByFileInfo(objFileInfo, strpSaveFname);
        //    //    return true;
        //    //}
        //    //if (File.Exists(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDir + strpFileNme))
        //    //{
        //    //    System.IO.FileInfo objFileInfo = new FileInfo(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDir + strpFileNme);
        //    //    FileDownByFileInfo(objFileInfo, strpSaveFname);
        //    //    return true;
        //    //}
        //    //if (File.Exists(HttpContext.Current.Server.MapPath(strpFileNme)))
        //    //{
        //    //    System.IO.FileInfo objFileInfo = new FileInfo(HttpContext.Current.Server.MapPath(strpFileNme));
        //    //    FileDownByFileInfo(objFileInfo, strpSaveFname);
        //    //    return true;
        //    //}
        //    //if (File.Exists(HttpContext.Current.Server.MapPath(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + strpFileNme)))
        //    //{
        //    //    System.IO.FileInfo objFileInfo = new FileInfo(HttpContext.Current.Server.MapPath(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + strpFileNme));
        //    //    FileDownByFileInfo(objFileInfo, strpSaveFname);
        //    //    return true;
        //    //}
        //    //if (!string.IsNullOrEmpty(strpFileId))
        //    //{
        //    //    System.IO.FileInfo objFileInfo = GetFileInfoByFileId(strpFileId, ref strpSaveFname, ref strpHasSeekServerList);
        //    //    if (objFileInfo != null && objFileInfo.Exists)
        //    //    {
        //    //        FileDownByFileInfo(objFileInfo, strpSaveFname);
        //    //        return true;
        //    //    }
        //    //}



        //    ////通过虚拟路径从备用服务器取
        //    //if (!string.IsNullOrEmpty(strpFileNme))
        //    //{
        //    //    string strFileBakServerList = Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_BAK_SERVER").Split(';')[0];
        //    //    if (!string.IsNullOrEmpty(strFileBakServerList) && strFileBakServerList.ToUpper() != Epm.AppLogic.Framework.EditConfig.GetAppSettings("F_CURR_SERVER").ToUpper())
        //    //    {
        //    //        if (strpHasSeekServerList.IndexOf(strFileBakServerList) == -1)
        //    //        {
        //    //            SRWebClient oSRWebClient = new SRWebClient();
        //    //            string strToFileName = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.RandomFileNme + strpFileNme.Substring(strpFileNme.LastIndexOf("."));
        //    //            string strSavetem1 = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strTemXmlFileDir + strToFileName;
        //    //            long lgFileLen = oSRWebClient.DownloadFile(strFileBakServerList + "filedown.axd?FILE_ID=" + strpFileId + "&file=" + strpFileNme + "&FSNME=" + strpSaveFname + "&USER_CRY=" + oSRWebClient.GetLoginUserCry() + "&SERVER_LIST=" + strpHasSeekServerList, strSavetem1, true);

        //    //            strpHasSeekServerList += string.IsNullOrEmpty(strpHasSeekServerList) ? strFileBakServerList : ";" + strFileBakServerList;

        //    //            if (lgFileLen > 0)
        //    //            {
        //    //                if (File.Exists(strSavetem1))
        //    //                {
        //    //                    FileDownByFileInfo(new FileInfo(strSavetem1), strpSaveFname);
        //    //                }
        //    //            }
        //    //        }
        //    //    }
        //    //}

        //    //return false;
        //}


        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="strFilePath">物理路径</param>
        //public void FileDownByFileInfo(System.IO.FileInfo objFileInfo, string strSaveFName)
        //{
        //    //HttpResponse Response = HttpContext.Current.Response;
        //    //System.IO.FileInfo aFile = new System.IO.FileInfo(filePath);
        //    //if (fileName == string.Empty)
        //    //{
        //    //    fileName = aFile.Name;
        //    //}
        //    //Response.Clear();
        //    //Response.ClearHeaders();
        //    //Response.BufferOutput = false;
        //    //Response.ContentType = "application/octet-stream";
        //    //Response.AppendHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
        //    //Response.AddHeader("Content-Length", aFile.Length.ToString());
        //    //Response.WriteFile(filePath);
        //    //Response.Flush();
        //    //Response.End();

        //    //Fdowntest(strFilePath);
        //    //return;






        //    //// Identify the file to download including its path.
        //    //string filepath = strFilePath;

        //    //System.IO.FileInfo objFileInfo = new System.IO.FileInfo(filepath);
        //    //// Identify the file name.
        //    string filename = objFileInfo.Name;// System.IO.Path.GetFileName(filepath);
        //    if (strSaveFName != string.Empty)
        //    {
        //        filename = strSaveFName + objFileInfo.Extension;
        //    }


        //    HttpContext.Current.Response.Clear();

        //    HttpContext.Current.Response.ClearHeaders();

        //    HttpContext.Current.Response.Buffer = false;
        //    HttpContext.Current.Response.Charset = "UTF-8";
        //    HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.UTF8;
        //    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
        //    HttpContext.Current.Response.ContentType = "application/octet-stream";


        //    //if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1)
        //    //{
        //    filename = System.Web.HttpUtility.UrlEncode(filename).Replace("+", "%20");
        //    //}
        //    if (HttpContext.Current.Request.UserAgent!= null && HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
        //    {
        //        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
        //    }
        //    else
        //    {
        //        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
        //    }
        //    //HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(filename).Replace("+", "%20"));

        //    HttpContext.Current.Response.AppendHeader("Content-Length", objFileInfo.Length.ToString());

        //    HttpContext.Current.Response.WriteFile(objFileInfo.FullName);

        //    HttpContext.Current.Response.Flush();

        //    HttpContext.Current.Response.End();
        //    //HttpContext.Current.ApplicationInstance.CompleteRequest();
        //    return;



        //    ////string strFile = "F:\\a.doc";//路径根据实际情况而定
        //    //HttpContext.Current.Response.Clear();
        //    //HttpContext.Current.Response.ClearHeaders();
        //    //HttpContext.Current.Response.Charset = "UTF-8";
        //    //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
        //    //HttpContext.Current.Response.ContentType = "application/octet-stream";
        //    //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlPathEncode(filename.Trim()));
        //    //HttpContext.Current.Response.WriteFile(strFilePath);
        //    //HttpContext.Current.Response.End();
        //    //return;


        //    //HttpContext.Current.Response.Clear();
        //    //bool success = ResponseFile(HttpContext.Current.Request, HttpContext.Current.Response, filename, filepath, 1024000);
        //    //HttpContext.Current.Response.End();

        //    //return;

        //    ////System.Web.HttpContext.Current.Response.Clear();
        //    ////System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition ", "attachment;filename= " + objFileInfo.Name);
        //    ////System.Web.HttpContext.Current.Response.AddHeader("Content-Length ", objFileInfo.Length.ToString());
        //    ////System.Web.HttpContext.Current.Response.ContentType = FileType;
        //    ////System.Web.HttpContext.Current.Response.WriteFile(objFileInfo.FullName);
        //    ////System.Web.HttpContext.Current.Response.End(); 








        //    try
        //    {
        //        using (System.IO.Stream iStream = objFileInfo.OpenRead())
        //        {

        //            // Buffer to read 10K bytes in chunk:
        //            byte[] buffer = new Byte[10240];

        //            // Length of the file:
        //            int length;

        //            // Total bytes to read:
        //            long dataToRead;
        //            //// Open the file.
        //            //iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
        //            //    System.IO.FileAccess.Read, System.IO.FileShare.Read);
        //            HttpContext.Current.Response.Clear();

        //            // Total bytes to read:
        //            dataToRead = iStream.Length;

        //            long p = 0;
        //            if (HttpContext.Current.Request.Headers["Range"] != null)
        //            {
        //                HttpContext.Current.Response.StatusCode = 206;
        //                p = long.Parse(HttpContext.Current.Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
        //            }
        //            if (p != 0)
        //            {
        //                HttpContext.Current.Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
        //            }
        //            HttpContext.Current.Response.AddHeader("Connection", "Keep-Alive");
        //            HttpContext.Current.Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
        //            HttpContext.Current.Response.ContentType = "application/octet-stream";
        //            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Microsoft.JScript.GlobalObject.encodeURIComponent(filename));

        //            iStream.Position = p;
        //            dataToRead = dataToRead - p;
        //            // Read the bytes.
        //            while (dataToRead > 0)
        //            {
        //                // Verify that the client is connected.
        //                if (HttpContext.Current.Response.IsClientConnected)
        //                {
        //                    // Read the data in buffer.
        //                    length = iStream.Read(buffer, 0, 10240);

        //                    // Write the data to the current output stream.
        //                    HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);

        //                    // Flush the data to the HTML output.
        //                    HttpContext.Current.Response.Flush();

        //                    buffer = new Byte[10240];
        //                    dataToRead = dataToRead - length;
        //                }
        //                else
        //                {
        //                    //prevent infinite loop if user disconnects
        //                    dataToRead = -1;
        //                }
        //            }
        //            iStream.Close();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        // Trap the error, if any.
        //        HttpContext.Current.Response.Write("Error : " + ex.Message);
        //    }
        //    finally
        //    {
        //        //if (iStream != null)
        //        //{
        //        //    //Close the file.
        //        //    iStream.Close();
        //        //}
        //        HttpContext.Current.Response.End();
        //    }

        //}

        //#endregion




        /// <summary>
        /// 获取附件显示列表
        /// </summary>
        /// <param name="strpRelId"></param>
        /// <returns></returns>
        public string GetAtachmentHtml(string strpRelId)
        {
            //string strLinkTemp = "<a href='{0}' target='_blank'><span>{1}</span></a>";
            string strLinkTemp3 = "<img src=\"" + SystemFileDir.FileDir.httpUrlBase + "images/attach.png\" height=\"14px\" align=\"absmiddle\" />   <a  href=\"javascript:void(0);return false;\" onclick=\"javascript:downfbyvp('{0}','','{1}');return false;\" target='_self'>{1}</a>";
            //string strLinkTemp2 = "<img src=\"" + strUrlHost + "images/desktop/Png16/tag.png\" height=\"14px\" align=\"absmiddle\" /> <a href=\"javascript:void(0)\" style=\"font-size:12pt;\" onclick=\"ShowChildForm(null,'{0}');return false;\" title=\"点击打开【{1}】!\"> {1}</a>";

            DataSet dsFile = SelectByRelationID(strpRelId);
            string strTable = "";
            for (int i = 0; i < dsFile.Tables[0].Rows.Count; i++)
            {
                strTable += "<div style=\"text-align:left;color: #009;margin-top:2px;margin-bottom:2px;\">【" + (i + 1).ToString() + "】&nbsp";
                strTable += string.Format(strLinkTemp3, dsFile.Tables[0].Rows[i]["FILE_V_PATH"].ToString(), "附件：" + dsFile.Tables[0].Rows[i]["FILE_NME"].ToString());

                strTable += "</div>";
            }
            return strTable;
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }
            drw["IS_DIR"] = drw["IS_DIR"].ToString() == "True";

            return true;
        }

        protected override bool AfterRowAdded(DataRow drw)
        {
            return true;
        }


        protected override bool AfterRowUpdate(DataRow drw)
        {
            return true;
        }


        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            }


            return true;
        }

        protected override bool BeforeRowDeletedR(DataRow drwSrc)
        {
            return true;
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="maxWidth">生成的缩略图最大宽度</param>
        /// <param name="maxHeight">生成的缩略图最大高度</param>
        /// <param name="imgFileStream">图片文件流对象</param>
        /// <param name="savePath">文件保存路径</param>
        /// <param name="imgFormat">生成图片的格式</param>
        public void GenerateThumbnail(int maxWidth, int maxHeight, System.IO.Stream imgFileStream, string savePath,
                                         System.Drawing.Imaging.ImageFormat imgFormat)
        {
            using (var img = System.Drawing.Image.FromStream(imgFileStream))
            {
                var sourceWidth = img.Width;
                var sourceHeight = img.Height;

                var thumbWidth = sourceWidth; //要生成的缩略图的宽度
                var thumbHeight = sourceHeight; //要生成的缩略图的高度

                //计算生成图片的高度和宽度
                if (sourceWidth > maxWidth || sourceHeight > maxHeight)
                {
                    var rateWidth = (double)sourceWidth / maxWidth;
                    var rateHeight = (double)sourceHeight / maxHeight;

                    if (rateWidth > rateHeight)
                    {
                        thumbWidth = maxWidth;
                        thumbHeight = (int)Math.Round(sourceHeight / rateWidth);
                    }
                    else
                    {
                        thumbWidth = (int)Math.Round(sourceWidth / rateHeight);
                        thumbHeight = maxHeight;
                    }
                }

                using (var bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight))
                {
                    //从Bitmap创建一个System.Drawing.Graphics对象，用来绘制高质量的缩小图。
                    using (var gr = System.Drawing.Graphics.FromImage(bmp))
                    {
                        //设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality
                        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //下面这个也设成高质量
                        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        //下面这个设成High
                        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

                        //把原始图像绘制成上面所设置宽高的缩小图
                        var rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
                        gr.DrawImage(img, rectDestination, 0, 0, sourceWidth, sourceHeight,
                                     System.Drawing.GraphicsUnit.Pixel);
                        //保存图像
                        bmp.Save(savePath, imgFormat);
                    }
                }
            }
        }

        //protected void Button4_Click(object sender, EventArgs e)
        //{
        //    GenerateThumbnail(500, 500, FileUpload1.PostedFile.InputStream, "d:/1.jpg",
        //                      System.Drawing.Imaging.ImageFormat.Jpeg);
        //}



        public DataSet SelectByRelTypeRelId(string strpRelType1, string strpRelType2, string strpRelId)
        {
            DataSet ds = DataObj.QueryBySQL("select * from " + this.TableName + " where ('" + strpRelType1 + "'= '' or RELATION_TYPE_CID1='" + strpRelType1 + "') and ('" + strpRelType2 + "'= '' or RELATION_TYPE_CID2='" + strpRelType2 + "') and RELATION_ID is not null and RELATION_ID<>'' and RELATION_ID='" + strpRelId + "'");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public DataSet SelectByRelationID(string strRelationId)
        {
            DataSet ds = null;
            ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE RELATION_ID='" + strRelationId + "'");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public string SetAtachmentHtml(DataSet dsFile, string strAction)
        {
            string strTable = "";
            //strTable += "<table border=\"0px\" cellpadding=\"0px\" cellspacing=\"0px\" >";//style=\"border: solid 1px #6588BA; width: 100%; \"
            if (dsFile == null || dsFile.Tables[0].Rows.Count <= 0)
            {
                strTable += "<div style=\" padding-left:10px;height:25px;\">未上传附件信息！</div>";
            }
            else
            {
                for (int i = 0; i < dsFile.Tables[0].Rows.Count; i++)
                {
                    if (dsFile.Tables[0].Rows[i].RowState != DataRowState.Deleted)
                    {
                        strTable += "<div style=\"text-align:left;color: #009;margin-top:2px;margin-bottom:2px;\">【" + (i + 1).ToString() + "】&nbsp";
                        if (dsFile.Tables[0].Rows[i]["FILE_EXT"].ToString().ToLower() == "rar")
                        {
                            strTable += "<img src=\"../images/logimg/log_rar.jpg\" width=\"20px\" height=\"20px\" style=\"vertical-align:middle\" alt=\"压缩文件\"/>";
                        }
                        else if (dsFile.Tables[0].Rows[i]["FILE_EXT"].ToString().ToLower() == "pdf")
                        {
                            strTable += "<img src=\"../images/logimg/log_pdf.jpg\" width=\"15px\" height=\"15px\" style=\"vertical-align:middle\" alt=\"pdf文档\"/>";
                        }
                        else if (dsFile.Tables[0].Rows[i]["FILE_EXT"].ToString().ToLower() == "docx" || dsFile.Tables[0].Rows[i]["FILE_EXT"].ToString().ToLower() == "doc")
                        {
                            strTable += "<img src=\"../images/logimg/log_word.jpg\" width=\"20px\" height=\"20px\" style=\"vertical-align:middle\" alt=\"word 文档\"/>";
                        }
                        else if (dsFile.Tables[0].Rows[i]["FILE_EXT"].ToString().ToLower() == "xlsx" || dsFile.Tables[0].Rows[i]["FILE_EXT"].ToString().ToLower() == "xls")
                        {
                            strTable += "<img src=\"../images/logimg/log_excel.jpg\" width=\"20px\" height=\"20px\" style=\"vertical-align:middle\" alt=\"excel 文档\"/>";
                        }
                        else
                        {
                            strTable += "<img src=\"../images/logimg/log_img.jpg\" width=\"20px\" height=\"20px\" style=\"vertical-align:middle\" alt=\"其他 文档\"/>";
                        }
                        strTable += "&nbsp<a onclick=\"ShowAttachmentView();\">附件名字：" + dsFile.Tables[0].Rows[i]["FILE_NME"].ToString() + "</a>";
                        if (!string.IsNullOrEmpty(dsFile.Tables[0].Rows[i]["FILE_SIZE"].ToString()))
                        {
                            int iFileSize = Convert.ToInt32(dsFile.Tables[0].Rows[i]["FILE_SIZE"].ToString());
                            string sTempS = (iFileSize / 1024).ToString();
                            sTempS = sTempS + "." + (iFileSize % 1024).ToString();
                            strTable += "&nbsp&nbsp附件大小：" + sTempS + " KB";
                        }
                        else
                        {
                            strTable += "&nbsp&nbsp附件大小：0 KB";
                        }
                        strTable += "&nbsp&nbsp&nbsp&nbsp<a onclick=\"DownLoadAtachment('" + dsFile.Tables[0].Rows[i]["FILE_V_PATH"].ToString() + "','" + dsFile.Tables[0].Rows[i]["FILE_NME"].ToString() + "')\" style=\"text-decoration:none;\">【下载地址】</a>";
                        if (strAction == "EDIT")
                        {
                            strTable += "&nbsp&nbsp&nbsp<a onclick=\"DeleteAtachment('" + dsFile.Tables[0].Rows[i]["FILE_ID"].ToString() + "')\" style=\"text-decoration:none;\">【删除文件】</a>";
                        }
                        strTable += "</div>";
                    }

                }
                //strTable += "<tr><td colspan=\"2\" style=\"height:20px;\"></td></tr>";
            }
            return strTable;
        }

        public string SelectFileHtml(string strOfceCde)
        {
            string strsql = "SELECT TOP 6 * FROM " + this.TableName + " A LEFT OUTER JOIN SYS_USER U ON A.INITIAL_USR=U.USER_CDE WHERE U.OFCE_CDE='" + strOfceCde + "' ORDER BY A.INITIAL_DT DESC";
            DataSet ds = null;
            ds = this.DataObj.QueryBySQL(strsql);
            string strTable = "";

            if (ds.Tables[0].Rows.Count > 0)
            {
                string strTitle = "";
                string[] ArryDate;
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    strTable += "<div style=\"text-align:left;border-bottom:dashed 1px #EBE8E1; width:98%; font-size:10pt;font-family:宋体; height:25px;\">&nbsp" + (i + 1).ToString() + ".&nbsp";
                    strTitle = ds.Tables[0].Rows[i]["FILE_NME"].ToString();
                    if (strTitle.Length > 15)
                    {
                        strTitle = strTitle.Substring(0, 15) + "..";
                    }
                    strTable += "&nbsp<a href=\"javascript:void(0);return false;\" onclick=\"javascript:downfbyvp('" + ds.Tables[0].Rows[i]["FILE_V_PATH"].ToString() + ds.Tables[0].Rows[i]["FILE_NME"].ToString() + "." + ds.Tables[0].Rows[i]["FILE_EXT"].ToString() + "');return false;\" style=\"text-decoration:none;text-align:left;\" target=\"_self\">" + strTitle + "</a>";

                    ArryDate = ds.Tables[0].Rows[i]["INITIAL_DT"].ToString().Split(' ');
                    strTable += "&nbsp&nbsp&nbsp日期：" + ArryDate[0] + "";
                    //strTable += "&nbsp&nbsp&nbsp<a onclick=\"DownLoadFile(|" + ds.Tables[0].Rows[i]["FILE_ID"].ToString() + "|)\" style=\"text-decoration:none;text-align:left;\">下载</a>";
                    strTable += "</div>";
                }

                strTable += "<div style=\"text-align:right;border-bottom:dashed 1px #EBE8E1;font-size:11pt;font-family:宋体;\"><a onclick=\"javascript:LookFileManage();return false;\" style=\"text-decoration:none;\">...More&nbsp&nbsp</a></div>";
            }
            else
            {
                strTable += "<div style=\"text-align:left;border-bottom:dashed 1px #EBE8E1;font-size:10pt;font-family:宋体;\">&nbsp不存在系统文件项</div>";
            }

            return strTable;
        }

        public DataSet SelectForFile(string strFileNO, string strFileArchiveTypeCid, string strStatus)
        {
            try
            {
                CDbParmCollection parmCollection = new CDbParmCollection();
                parmCollection.Add(new CDbParm("strFileNO", ParameterDirection.Input, EDbType.String, 36, strFileNO));
                parmCollection.Add(new CDbParm("strFileArchiveTypeCid", ParameterDirection.Input, EDbType.String, 20, strFileArchiveTypeCid));
                parmCollection.Add(new CDbParm("strStatus", ParameterDirection.Input, EDbType.String, 2, strStatus));
                parmCollection.Add(new CDbParm("strUser", ParameterDirection.Input, EDbType.String, 36, msBsc.SvRef.UserInfo.Operator));

                DataSet ds = this.DataObj.QueryBySP("SYS_SELECT_USER_FILE_FOR_FINDER", parmCollection);
                ds.Tables[0].TableName = this.TableName;
                return ds;
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }

        public DataSet SelectByFileName(string strFileName)
        {
            try
            {
                CDbParmCollection parmCollection = new CDbParmCollection();
                parmCollection.Add(new CDbParm("strFileNme", ParameterDirection.Input, EDbType.String, 200, strFileName));
                parmCollection.Add(new CDbParm("strUser", ParameterDirection.Input, EDbType.String, 36, msBsc.SvRef.UserInfo.Operator));
                DataSet ds = this.DataObj.QueryBySP("SYS_SELECT_BY_FILE_NME", parmCollection);
                ds.Tables[0].TableName = this.TableName;
                return ds;
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }

        public DataSet SelectByImgClass(string strImgClass)
        {
            try
            {
                string strSql = "SELECT A.*,B.CLASSIFY_NME FROM " + this.TableName + " A LEFT OUTER JOIN SHP_GOODS_IMG_CLASSIFY B ON A.RELATION_TYPE_CID2=B.IMG_CLASSIFY_ID WHERE A.RELATION_TYPE_CID1='1' AND A.USER_NME = '" + msBsc.SvRef.UserInfo.Operator + "'";
                if (!string.IsNullOrEmpty(strImgClass))
                {
                    strSql += "AND A.RELATION_TYPE_CID2='" + strImgClass + "'";
                }
                strSql += " ORDER BY A.FILE_NO";
                DataSet ds = this.DataObj.QueryBySQL(strSql, null);
                ds.Tables[0].TableName = this.TableName;
                return ds;
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }

        public DataSet SelectForSysImgMana(string strParentId)
        {
            try
            {
                string strSql = "SELECT FILE_ID,FILE_NME,FILE_EXT,SERVER_HTTP,FILE_V_PATH,IS_DIR,REC_UPDATE_DT FROM SYS_FILE WHERE RELATION_TYPE_CID1='0' AND RELATION_TYPE_CID2='0' AND PARENT_FILE_ID='" + strParentId + "'";
                strSql += " ORDER BY REC_UPDATE_DT DESC";
                DataSet ds = this.DataObj.QueryBySQL(strSql, null);
                ds.Tables[0].TableName = this.TableName;
                return ds;
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }

        public DataSet SelectForCustomerImgMana(string strParentId, string strUserNme)
        {
            try
            {
                string strSql = "SELECT FILE_ID,FILE_NME,FILE_EXT,SERVER_HTTP,FILE_V_PATH,IS_DIR,REC_UPDATE_DT FROM SYS_FILE WHERE USER_NME='" + strUserNme + "' AND RELATION_TYPE_CID1='1' AND RELATION_TYPE_CID2='0' AND PARENT_FILE_ID='" + strParentId + "'";
                strSql += " ORDER BY IS_DIR DESC,REC_UPDATE_DT DESC";
                DataSet ds = this.DataObj.QueryBySQL(strSql, null);
                ds.Tables[0].TableName = this.TableName;
                return ds;
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
            }
        }

        /// <summary>
        /// 从已知路径保存文件,返回新的虚拟路径
        /// </summary>
        /// <param name="strFileId"></param>
        /// <param name="strRelId"></param>
        /// <param name="strType1"></param>
        /// <param name="strImgClass"></param>
        /// <param name="strServerHttp"></param>
        /// <param name="strVpath">虚拟路径</param>
        /// <param name="strpath">物理路径</param>
        /// <param name="blCopy">是否拷贝到永久目录</param>
        public string SaveImgToServer(string strFileId, string strRelId, string strType1, string strImgClass, string strServerHttp, string strVpath, string strpath, bool blCopy = true)
        {
            if (string.IsNullOrEmpty(strpath) && !string.IsNullOrEmpty(strVpath))
            {
                strpath = HttpContext.Current.Server.MapPath(strVpath);
                if (string.IsNullOrEmpty(strpath))
                {
                    strpath = HttpContext.Current.Server.MapPath(msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + strVpath);
                    if (!string.IsNullOrEmpty(strpath))
                    {
                        strVpath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + strVpath;
                    }
                }
            }
            if (string.IsNullOrEmpty(strpath))
            {
                return "";
            }

            DataSet dsSysFile = null;
            DataRow drSysFile = null;
            if (!string.IsNullOrEmpty(strFileId))
            {
                dsSysFile = this.SelectById(strFileId);
                if (dsSysFile.Tables[0].Rows.Count > 0)
                {
                    drSysFile = dsSysFile.Tables[0].Rows[0];
                }
            }
            if (dsSysFile == null || dsSysFile != null && dsSysFile.Tables[0].Rows.Count <= 0)
            {
                dsSysFile = this.SelectByRelTypeRelId(strType1, strImgClass, strRelId);
                if (dsSysFile.Tables[0].Rows.Count <= 0)
                {
                    drSysFile = dsSysFile.Tables[0].NewRow();
                    drSysFile["RELATION_ID"] = strRelId;
                    drSysFile["RELATION_TYPE_CID1"] = strType1;
                    drSysFile["RELATION_TYPE_CID2"] = strImgClass;
                    drSysFile["FILE_ID"] = this.DataObj.NewID();
                    drSysFile["USER_NME"] = msBsc.SvRef.UserInfo.Operator;
                    dsSysFile.Tables[0].Rows.Add(drSysFile);
                }
                else
                {
                    drSysFile = dsSysFile.Tables[0].Rows[0];
                }
            }
            if (drSysFile["FILE_V_PATH"].ToString() != string.Empty && drSysFile["FILE_V_PATH"].ToString() == strVpath)
            {
                return drSysFile["FILE_V_PATH"].ToString();
            }
            if (string.IsNullOrEmpty(strVpath) || blCopy)
            {
                string fileExt = Path.GetExtension(strpath).ToLower();
                string filename = msBsc.SvRef.ApplicationConst.Const.GenerateStrId() + fileExt;
                strVpath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDirV + filename;
                System.IO.File.Copy(strpath, HttpContext.Current.Server.MapPath(strVpath));
            }

            System.IO.FileInfo ofinfo = new FileInfo(strpath);
            drSysFile["FILE_NO"] = "";
            drSysFile["FILE_NME"] = ofinfo.Name;
            drSysFile["SERVER_HTTP"] = strServerHttp;
            drSysFile["FILE_V_PATH"] = strVpath;
            drSysFile["FILE_EXT"] = ofinfo.Extension.Replace(".", "");
            drSysFile["FILE_SIZE"] = ofinfo.Length / 1024;


            if (dsSysFile.HasChanges())
            {
                this.Update(dsSysFile);
            }

            return strVpath;

        }



        public int SaveAsPostFile(HttpPostedFile file, string strToPath)
        {

            //开始上传
            string path = strToPath;
            int iFSize = 0;
            //FileUpload1.SaveAs(Server.MapPath(path));//SaveAs 方法是一次性把文件上传到服务器，不适合大文件上传，可能把服务器卡死
            //应该用流来上传大文件
            Stream s = file.InputStream;//把文件的数据读取到st流中

            //创建一个文件流来把上传的文件写入到服务器上
            FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
            byte[] buffer = new byte[1024];//缓冲区
            int readLen;//每次真正读取到的字节数
            while ((readLen = s.Read(buffer, 0, 1024)) > 0)
            {
                //读到数据了(此时独到的数据在buffer缓冲区中)
                //开始把文件写入到服务器的磁盘中

                fs.Write(buffer, 0, readLen);
            }
            iFSize = (int)(fs.Length / 1024);
            fs.Flush();//请空缓冲区，使得所有缓冲区的数据都写入到文件中
            s.Flush();
            fs.Close();//关闭流，释放资源
            s.Close();

            return iFSize;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="file"></param>
        /// <param name="strRelId">关联表ID</param>
        /// <param name="strType1">文件分组类型，0系统文件，1用户文件</param>
        /// <param name="strImgClass">文件自定义分类，如系统文件的下级分类，用户文件的自定义分类</param>
        /// <param name="strServerHttp">文件所在服务器</param>
        /// <returns></returns>
        public string SaveImgToServer(HttpPostedFile file, string strFileId, string strRelId, string strType1, string strImgClass, string strServerHttp, string strParentId, bool blDir, string strDirNme, bool blUTF8 = false)
        {
            string strFNme = "", ext = "", filename = "", strVpath = "";
            int iFSize = 0;
            if (file != null)
            {
                string strPostFileNme = file.FileName;
                if (blUTF8)
                {
                    strPostFileNme = msBsc.SvRef.CString.StrEncodingConvert(strPostFileNme, System.Text.Encoding.UTF8, System.Text.Encoding.GetEncoding("GBK")).Replace("?", "");
                }
                strFNme = strPostFileNme.Substring(0, strPostFileNme.LastIndexOf('.'));

                ext = strPostFileNme.Substring(strPostFileNme.LastIndexOf('.') + 1);
                filename = msBsc.SvRef.ApplicationConst.Const.GenerateStrId() + "." + ext;
                strVpath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDirV + filename;
                //file.SaveAs(HttpContext.Current.Server.MapPath(strVpath));
                //iFSize = file.ContentLength / 1024;

                //file.InputStream.Dispose();
                //file.InputStream.Close();
                string path = HttpContext.Current.Server.MapPath(strVpath);
                iFSize = SaveAsPostFile(file, path);
            }
            else
            {
                strFNme = strDirNme;
            }
            //DataSet dsSysFile = objSysFile.SelectEndImg();
            //int iFileNo = 0;
            //if (dsSysFile.Tables[0].Rows.Count > 0)
            //{
            //    iFileNo = Convert.ToInt32(dsSysFile.Tables[0].Rows[dsSysFile.Tables[0].Rows.Count - 1]["FILE_NO"].ToString()) + 1;
            //}
            DataSet dsSysFile;
            DataRow drSysFile;
            if (string.IsNullOrEmpty(strFileId))
            {
                dsSysFile = new CDmSysFile();
                drSysFile = dsSysFile.Tables[0].NewRow();
                drSysFile["RELATION_ID"] = strRelId;
                drSysFile["PARENT_FILE_ID"] = strParentId;
                drSysFile["IS_DIR"] = blDir;
                drSysFile["RELATION_TYPE_CID1"] = strType1;
                drSysFile["RELATION_TYPE_CID2"] = strImgClass;
                drSysFile["FILE_ID"] = this.DataObj.NewID();
                drSysFile["USER_NME"] = msBsc.SvRef.UserInfo.Operator;
                dsSysFile.Tables[0].Rows.Add(drSysFile);
            }
            else
            {
                dsSysFile = this.SelectById(strFileId);
                if (dsSysFile.Tables[0].Rows.Count > 0)
                {
                    drSysFile = dsSysFile.Tables[0].Rows[0];
                    if (drSysFile["FILE_V_PATH"].ToString() != string.Empty)
                    {
                        System.IO.FileInfo ofinfo = new FileInfo(HttpContext.Current.Server.MapPath(drSysFile["FILE_V_PATH"].ToString()));
                        if (ofinfo.Exists)
                        {
                            ofinfo.Delete();
                        }
                    }
                }
                else
                {
                    drSysFile = dsSysFile.Tables[0].NewRow();
                    drSysFile["RELATION_ID"] = strRelId;
                    drSysFile["PARENT_FILE_ID"] = strParentId;
                    drSysFile["IS_DIR"] = blDir;
                    drSysFile["RELATION_TYPE_CID1"] = strType1;
                    drSysFile["RELATION_TYPE_CID2"] = strImgClass;
                    drSysFile["FILE_ID"] = this.DataObj.NewID();
                    drSysFile["USER_NME"] = msBsc.SvRef.UserInfo.Operator;
                    dsSysFile.Tables[0].Rows.Add(drSysFile);
                }
            }
            drSysFile["FILE_NO"] = "";
            drSysFile["FILE_NME"] = strFNme;
            drSysFile["SERVER_HTTP"] = strServerHttp;
            drSysFile["FILE_V_PATH"] = strVpath;
            drSysFile["FILE_EXT"] = ext;
            drSysFile["FILE_SIZE"] = iFSize;


            if (dsSysFile.HasChanges())
            {
                this.Update(dsSysFile);
            }
            return "{\"error\":0,\"url\":\"" + HttpTools.stringToJson(strVpath) + "\",\"fid\":\"" + drSysFile["FILE_ID"].ToString() + "\",\"message\":\"\"}";
        }



        public string SaveImgToServer(string strImgbase64, string strPostFileNme, string strFileId, string strRelId, string strType1, string strImgClass, string strServerHttp, string strParentId, bool blDir, string strDirNme, bool blUTF8 = false)
        {
            string strFNme = "", ext = "", filename = "", strVpath = "";
            int iFSize = 0;
            if (strImgbase64 != string.Empty)
            {


                //string strPostFileNme = file.FileName;
                if (blUTF8)
                {
                    strPostFileNme = msBsc.SvRef.CString.StrEncodingConvert(strPostFileNme, System.Text.Encoding.UTF8, System.Text.Encoding.GetEncoding("GBK")).Replace("?", "");
                }
                strFNme = strPostFileNme.Substring(0, strPostFileNme.LastIndexOf('.'));

                ext = strPostFileNme.Substring(strPostFileNme.LastIndexOf('.') + 1);
                filename = msBsc.SvRef.ApplicationConst.Const.GenerateStrId() + "." + ext;
                strVpath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDirV + filename;
                //file.SaveAs(HttpContext.Current.Server.MapPath(strVpath));
                //iFSize = file.ContentLength / 1024;

                //file.InputStream.Dispose();
                //file.InputStream.Close();
                string path = HttpContext.Current.Server.MapPath(strVpath);

                //保存

                byte[] bytes = Convert.FromBase64String(strImgbase64);
                using (MemoryStream memStream = new MemoryStream(bytes))
                {

                    iFSize = bytes.Length / 1024;
                    //return "{\"error\":1,\"url\":\"\",\"fid\":\"\",\"message\":\"" + iFSize + "\"}";
                    //if (iFSize>1000)
                    //{
                    //    return "{\"error\":1,\"url\":\"\",\"fid\":\"\",\"message\":\""+iFSize+"\"}";
                    //}
                    //BinaryFormatter binFormatter = new BinaryFormatter();
                    using (System.Drawing.Image img = System.Drawing.Image.FromStream(memStream))
                    {
                        img.Save(path);
                        //img.Dispose();
                    }
                    //memStream.Dispose();
                    //using (System.Drawing.Image img = (System.Drawing.Image)binFormatter.Deserialize(memStream))
                    //{
                    //    img.Save(path);
                    //}

                }


                //iFSize = SaveAsPostFile(file, path);
            }
            else
            {
                throw new Exception("参数错误！");
                strFNme = strDirNme;
            }
            //DataSet dsSysFile = objSysFile.SelectEndImg();
            //int iFileNo = 0;
            //if (dsSysFile.Tables[0].Rows.Count > 0)
            //{
            //    iFileNo = Convert.ToInt32(dsSysFile.Tables[0].Rows[dsSysFile.Tables[0].Rows.Count - 1]["FILE_NO"].ToString()) + 1;
            //}
            DataSet dsSysFile;
            DataRow drSysFile;
            if (string.IsNullOrEmpty(strFileId))
            {
                dsSysFile = new CDmSysFile();
                drSysFile = dsSysFile.Tables[0].NewRow();
                drSysFile["RELATION_ID"] = strRelId;
                drSysFile["PARENT_FILE_ID"] = strParentId;
                drSysFile["IS_DIR"] = blDir;
                drSysFile["RELATION_TYPE_CID1"] = strType1;
                drSysFile["RELATION_TYPE_CID2"] = strImgClass;
                drSysFile["FILE_ID"] = this.DataObj.NewID();
                drSysFile["USER_NME"] = msBsc.SvRef.UserInfo.Operator;
                dsSysFile.Tables[0].Rows.Add(drSysFile);
            }
            else
            {
                dsSysFile = this.SelectById(strFileId);
                if (dsSysFile.Tables[0].Rows.Count > 0)
                {
                    drSysFile = dsSysFile.Tables[0].Rows[0];
                    if (drSysFile["FILE_V_PATH"].ToString() != string.Empty)
                    {
                        System.IO.FileInfo ofinfo = new FileInfo(HttpContext.Current.Server.MapPath(drSysFile["FILE_V_PATH"].ToString()));
                        if (ofinfo.Exists)
                        {
                            ofinfo.Delete();
                        }
                    }
                }
                else
                {
                    drSysFile = dsSysFile.Tables[0].NewRow();
                    drSysFile["RELATION_ID"] = strRelId;
                    drSysFile["PARENT_FILE_ID"] = strParentId;
                    drSysFile["IS_DIR"] = blDir;
                    drSysFile["RELATION_TYPE_CID1"] = strType1;
                    drSysFile["RELATION_TYPE_CID2"] = strImgClass;
                    drSysFile["FILE_ID"] = this.DataObj.NewID();
                    drSysFile["USER_NME"] = msBsc.SvRef.UserInfo.Operator;
                    dsSysFile.Tables[0].Rows.Add(drSysFile);
                }
            }
            drSysFile["FILE_NO"] = "";
            drSysFile["FILE_NME"] = strFNme;
            drSysFile["SERVER_HTTP"] = strServerHttp;
            drSysFile["FILE_V_PATH"] = strVpath;
            drSysFile["FILE_EXT"] = ext;
            drSysFile["FILE_SIZE"] = iFSize;


            if (dsSysFile.HasChanges())
            {
                this.Update(dsSysFile);
            }
            return "{\"error\":0,\"url\":\"" + HttpTools.stringToJson(strVpath) + "\",\"fid\":\"" + drSysFile["FILE_ID"].ToString() + "\",\"message\":\"\"}";
        }

        public DataSet SelectByIds(string strIdS)
        {
            DataSet ds = this.DataObj.QueryBySQL("SELECT * FROM " + this.TableName + " WHERE  " + this.KeyFieldName + " IN  ('" + strIdS.Replace("'", "").Replace(",", "','") + "')");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        public void DeleteFilesByIds(string strIdS)
        {
            DataSet ds = SelectByIds(strIdS);
            for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            {
                if (ds.Tables[0].Rows[i]["IS_DIR"].ToString() == "True")
                {
                    DataSet dsc = this.DataObj.QueryBySQL("SELECT COUNT_R=COUNT(*) FROM SYS_FILE WHERE PARENT_FILE_ID='" + ds.Tables[0].Rows[i]["FILE_ID"].ToString() + "'");
                    if (dsc.Tables[0].Rows.Count > 0 && (int)(dsc.Tables[0].Rows[0]["COUNT_R"]) > 0)
                    {
                        throw new Exception("当前目录下存在文件，不能被删除！");
                    }
                }
                if (ds.Tables[0].Rows[i]["FILE_V_PATH"].ToString() != string.Empty)
                {
                    System.IO.FileInfo ofinfo = new FileInfo(HttpContext.Current.Server.MapPath(ds.Tables[0].Rows[i]["FILE_V_PATH"].ToString()));
                    if (ofinfo.Exists)
                    {
                        ofinfo.Delete();
                    }
                }
                ds.Tables[0].Rows[i].Delete();
            }
            this.Update(ds);
        }

        public string SaveBase64ImgServer(string strImgbase64, string strPostFileNme, bool blUTF8 = false)
        {
            string strFNme = "", ext = "", filename = "", strVpath = "";
            int iFSize = 0;
            if (strImgbase64 != string.Empty)
            {

                if (blUTF8)
                {
                    strPostFileNme = msBsc.SvRef.CString.StrEncodingConvert(strPostFileNme, System.Text.Encoding.UTF8, System.Text.Encoding.GetEncoding("GBK")).Replace("?", "");
                }
                strFNme = strPostFileNme.Substring(0, strPostFileNme.LastIndexOf('.'));

                ext = strPostFileNme.Substring(strPostFileNme.LastIndexOf('.') + 1);
                filename = msBsc.SvRef.ApplicationConst.Const.GenerateStrId() + "." + ext;
                strVpath = msBsc.AppLogic.Cfg.SystemFileDir.FileDir.UrlBase + msBsc.AppLogic.Cfg.SystemFileDir.FileDir.strSaveUploadSysFileDirV + filename;
                //file.SaveAs(HttpContext.Current.Server.MapPath(strVpath));
                //iFSize = file.ContentLength / 1024;

                //file.InputStream.Dispose();
                //file.InputStream.Close();
                string path = HttpContext.Current.Server.MapPath(strVpath);

                //保存

                byte[] bytes = Convert.FromBase64String(strImgbase64);
                using (MemoryStream memStream = new MemoryStream(bytes))
                {

                    iFSize = bytes.Length / 1024;
                    using (System.Drawing.Image img = System.Drawing.Image.FromStream(memStream))
                    {
                        img.Save(path);
                    }
                }
            }
            else
            {
                throw new Exception("参数错误！");
                strFNme = "";
            }
            return strVpath;
        }
    }
}
